package com.xiao.androidcompose01.screen.main

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.view.View
import android.webkit.ConsoleMessage
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import cafe.adriel.voyager.koin.koinScreenModel
import cafe.adriel.voyager.navigator.LocalNavigator
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabOptions
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.tencent.rtmp.ui.TXCloudVideoView
import com.xiao.androidcompose01.LocalAccountData
import com.xiao.androidcompose01.api.data.AccountData
import com.xiao.androidcompose01.ui.theme.MainColor
import com.xiao.androidcompose01.viewmodel.TencentRoomModel
import com.xiao.androidcompose01.viewmodel.TencentRoomModel.MsgLevel
import com.xiao.androidcompose01.weight.OperateButton
import com.xiao.androidcompose01.weight.click
import org.koin.core.context.startKoin
import org.koin.ksp.generated.defaultModule


class HomeTab : Tab {
   override val options: TabOptions
      @Composable
      get() {
         val title = "房间"
         val icon = rememberVectorPainter(Icons.Default.Home)
         
         return remember {
            TabOptions(
               index = 0u,
               title = title,
               icon = icon
            )
         }
      }
   
   @OptIn(ExperimentalPermissionsApi::class)
   @Composable
   override fun Content() {
      val accountData = LocalAccountData.current
      val context = LocalContext.current
      val tencentRoomViewModel = koinScreenModel<TencentRoomModel>()
      var cloudView by remember { mutableStateOf<TXCloudVideoView?>(null) }
      val cmd by tencentRoomViewModel.tencentCmdScreen.collectAsStateWithLifecycle()
      val tencentMsg by tencentRoomViewModel.tencentMsg.collectAsStateWithLifecycle()
      val userController by tencentRoomViewModel.userController.collectAsStateWithLifecycle()
      var permissionStateMsg by remember { mutableStateOf("") }
      val permissionState = rememberMultiplePermissionsState(
         permissions = listOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
         )
      )
      val locationPermissionState = rememberMultiplePermissionsState(
         permissions = listOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
         )
      )
      LaunchedEffect(Unit) {
         println("申请定位权限")
         locationPermissionState.launchMultiplePermissionRequest()
      }
      if (permissionState.allPermissionsGranted){
         permissionStateMsg = ""
      }else{
         permissionStateMsg = "您有权限未赋予"
      }
      permissionState.revokedPermissions.forEach {
         println(it)
      }
      LaunchedEffect(Unit) {
         if (!permissionState.allPermissionsGranted){
            permissionState.launchMultiplePermissionRequest()
         }
      }
      
      LaunchedEffect(Unit) {
         tencentRoomViewModel.updateLocalView()
         tencentRoomViewModel.enterRoom(accountData)
      }
      if (locationPermissionState.allPermissionsGranted){
         tencentRoomViewModel.startLocation(accountData,null)
      }
      if (cmd!=null && cloudView!=null){
         tencentRoomViewModel.startRemoteView(cloudView!!)
//         cloud.startRemoteView(
//            remoteUserId,
//            p1,view)
      }
      Box(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) {
         
         AndroidView(
            factory = { context ->
               val view = TXCloudVideoView(context)
               cloudView = view
               tencentRoomViewModel.cacheView = view
               view
            }, update = { view ->
            },
            modifier = Modifier
               .fillMaxSize()
         )
         cloudView?.let {
            if (userController.showCamera){
               it.visibility = View.VISIBLE
            }   else{
               it.visibility = View.INVISIBLE
            }
         }
         
         Column {
            if (accountData.isParent()){
               Row(Modifier.fillMaxWidth()) {
                  
                  val nextCameraCmd: Boolean
                  val cameraTxt = if (userController.showCamera){
                     nextCameraCmd = false
                     "隐藏照相机"
                  }else{
                     nextCameraCmd = true
                     "查看照相机"
                  }
                  OperateButton(Modifier.weight(1f), text = cameraTxt,true,){
                     tencentRoomViewModel.showOrHiddenCamera(nextCameraCmd)
                  }
                  Spacer(Modifier.weight(0.5f))
                  val nextVideoCmd: Boolean
                  val soundTxt = if (userController.playSound){
                     nextVideoCmd = false
                     "播放"
                  }else{
                     nextVideoCmd = true
                     "静音"
                  }
                  OperateButton(Modifier.weight(1f), text = soundTxt,true){
                     tencentRoomViewModel.muteVolume(nextVideoCmd)
                  }
               }
               Spacer(Modifier.height(20.dp))
            }
            
            if (permissionStateMsg.isNotBlank()){
               TipLayout(message = MsgLevel.ERROR to permissionStateMsg, modifier = Modifier.click(true){
                  if (permissionState.shouldShowRationale){
                     permissionState.launchMultiplePermissionRequest()
                  }else{
                     val intent = Intent()
                     intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                     val uri = Uri.fromParts("package", context.packageName, null)
                     intent.setData(uri)
                     context.startActivity(intent)
                  }
                  
               })
            }
            if (tencentMsg.second.isNotBlank()){
               TipLayout(message = tencentMsg)
            }
            if (accountData.isParent()){
               ParentMenu(onSharedScreen = {
                  tencentRoomViewModel.cmdScreenCapture()
               },onShareCamera = {
                  tencentRoomViewModel.cmdCameraCapture()
               })
            }
         }
         
         
      }
   }
   
   @Composable
   fun OperaLayout(modifier: Modifier = Modifier) {
      
   }
   
   @Composable
   fun TipLayout(modifier: Modifier = Modifier,message: Pair<MsgLevel, String>) {
      val color = when(message.first){
         MsgLevel.INFO -> Color.Blue
         MsgLevel.SUCCESS -> Color.Green
         MsgLevel.ERROR -> Color.Red
      }
      Row(modifier
         .fillMaxWidth()
         .background(Color.White.copy(0.5f))
         .padding(vertical = 5.dp, horizontal = 12.dp)) {
         Text(message.second, color = color, fontSize = 12.sp)
      }
   }
   
   @Composable
   fun ParentMenu(modifier: Modifier = Modifier,onSharedScreen:()-> Unit,
                  onShareCamera:()-> Unit) {
      Row(modifier) {
         OperateButton(Modifier.weight(1f), text = "查看屏幕共享",true,onSharedScreen)
         Spacer(Modifier.weight(0.5f))
         OperateButton(Modifier.weight(1f), text = "查看摄像",true,onShareCamera)
      }
   }
}


@Preview
@Composable
private fun HomeTabPreview() {
   val tempAccount = AccountData(
      "","", 0,"","","",
      "","孩子","",arrayListOf("",""),
   )
   startKoin {
      modules(defaultModule)
   }
   CompositionLocalProvider(LocalNavigator provides null,
      LocalAccountData provides tempAccount
   ) {
      val homeTab = HomeTab()
//      val tencentRoomViewModel = koinViewModel<TencentRoomModel>()
      Column {
         homeTab.TipLayout(message = MsgLevel.ERROR to "测试消息")
         homeTab.ParentMenu(onSharedScreen = {
         
         }, onShareCamera = {
         
         })
      }
      
   }
   
}

